<template>
  <el-card class="box-card"
           shadow="never">
    <!-- <div class="oper-status"> {{editStatus ? '编辑' : '新增'}} </div> -->
    <div class="oper-status"> {{titleName}} </div>
    <el-form ref="ruleForm"
             :model="ruleForm"
             :rules="rules"
             label-width="80px"
             class="demo-ruleForm">
      <el-row>
        <el-form-item label="起点城市"
                      prop="fromAddress">
          <el-col :span="22">
            <!-- <area-select ref="panel"
                         v-model="ruleForm.startCity"
                         clearable
                         type="code"
                         :area-values="ruleForm.startCity"
                         :disabled="disabled || isFromLock"
                         placeholder="请选择起点城市"
                         check-strictly
                         @confirm="changeFrom" /> -->
            <area-cascader v-model="ruleForm.fromAddress"
                           :props="props"
                           :disabled="disabled || isFromLock"
                           :placeholder="`请选择起点城市`"
                           @input="changeFrom" />
          </el-col>
          <!-- <el-col :span="12">
            <el-input v-model="ruleForm.startAddress"
                      :disabled="disabled || startCityDisabled || isFromLock"
                      placeholder="请输入详细地址" />
          </el-col> -->
          <el-col :span="2"
                  class="lock">
            <el-button type="text"
                       @click="handerFromLock">{{`${isFromLock ? '解锁' : '锁定'}`}}</el-button>
          </el-col>
        </el-form-item>
        <el-form-item prop="startAddress">
          <el-input v-model="ruleForm.startAddress"
                    :rows="2"
                    type="textarea"
                    :disabled="disabled || startCityDisabled || isFromLock"
                    placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="目的城市"
                      prop="toAddress">
          <el-col :span="22">
            <!-- <area-select ref="endSelect"
                         v-model="ruleForm.endCity"
                         clearable
                         type="code"
                         :disabled="disabled || isEndLock"
                         :area-values="ruleForm.endCity"
                         placeholder="请选择目的城市"
                         check-strictly
                         @confirm="changeTo" /> -->
            <area-cascader v-model="ruleForm.toAddress"
                           :props="props"
                           :disabled="disabled || isEndLock"
                           :placeholder="`请选择目的城市`"
                           @input="changeTo" />
          </el-col>
          <!-- <el-col :span="12">
            <el-input v-model="ruleForm.endAddress"
                      :disabled="disabled || endCityDisabled || isEndLock"
                      placeholder="请输入详细地址" />
          </el-col> -->
          <el-col :span="2"
                  class="lock">
            <el-button type="text"
                       @click="handerEndLock">{{`${isEndLock ? '解锁' : '锁定'}`}}</el-button>
          </el-col>
        </el-form-item>
        <el-form-item prop="endAddress">
          <el-input v-model="ruleForm.endAddress"
                    :rows="2"
                    type="textarea"
                    :disabled="disabled || endCityDisabled || isEndLock"
                    placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="车型"
                      prop="vehicleModel">
          <VehicleSelect v-model="ruleForm.vehicleModel"
                         :disabled="disabled"
                         @input="handerInput" />
        </el-form-item>
        <el-form-item v-if="ruleForm.vehicleOptions || ruleForm.vehicleLength"
                      prop="vehicleLength"
                      label="车身长">
          <div class="vehicle-flex">
            <el-select v-model="ruleForm.vehicleLength"
                       :disabled="disabled"
                       style="width: 120px"
                       placeholder="请选择车身长"
                       @change="handerVehicleLength">
              <el-option v-for="item in ruleForm.vehicleOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
            <div v-if="ruleForm.vehicleVolume && ruleForm.vehicleLength != 999"
                 class="vehicle-right">
              <span>{{ `最大承载：体积 ${ruleForm.vehicleVolume} m³，重量 ${ruleForm.vehicleWeight} t` }}</span>
            </div>
          </div>
        </el-form-item>
        <el-col v-if="ruleForm.vehicleLength === 999"
                :span="12"
                class="show-item">
          <el-form-item key="vehicleVolume"
                        label="容积"
                        prop="vehicleVolume">
            <el-input v-model="ruleForm.vehicleVolume"
                      :disabled="disabled"
                      placeholder="输入容积"
                      @input="inputUpdate($event)">
              <span slot="suffix">立方米</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="ruleForm.vehicleLength === 999"
                :span="12"
                class="show-item">
          <el-form-item key="vehicleWeight"
                        label="载重"
                        prop="vehicleWeight">
            <el-input v-model="ruleForm.vehicleWeight"
                      :disabled="disabled"
                      placeholder="输入载重"
                      @input="inputUpdate($event)">
              <span slot="suffix">吨</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="价格"
                        prop="price">
            <el-input v-model="ruleForm.price"
                      placeholder="请输入内容">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="时效"
                        prop="days">
            <el-input v-model="ruleForm.days"
                      :disabled="disabled"
                      :min="1"
                      type="number"
                      placeholder="请输入时效天数">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="bargaStatus"
                :span="24">
          <el-form-item label="备注"
                        prop="remarks">
            <el-input v-model="ruleForm.remarks"
                      type="textarea"
                      :rows="2"
                      placeholder="请输入内容">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary"
                   @click="submitForm('ruleForm')">保存</el-button>
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import VehicleSelect from './VehicleSelect.vue'
// import AreaSelect from "@basic/area/AreaSelect";
import AreaCascader from "@basic/area/AreaCascader.vue";

export default {
  name: 'AddVehicleBox',
  components: { VehicleSelect, AreaCascader },
  props: {
    value: {
      type: Object,
      default: () => { }
    },
    bargaStatus: {
      type: [String, Number],
      default: null
    },
    editStatus: {
      type: Boolean,
      default: false
    }
  },
  data () {
    const validateAgingDays = (rule, value, callback) => {
      let pattern = /^[1-9]\d*$/;
      if (!value) {
        return callback(new Error('请输入时效天数'))
      }
      setTimeout(() => {
        if (Number(value) > 30) {
          return callback(new Error('时效天数只能输入1-30数字'))
        } else if (!pattern.test(value)) {
          return callback(new Error('只能输入整数'))
        }
        else {
          callback()
        }
      }, 100)
    }
    return {
      ruleForm: {
        startAddress: '',
        endAddress: '',
        vehicleVolume: '',
        vehicleWeight: ''
      },
      headTitle: null,
      pressLoadLabel: null,
      startCityDisabled: true,
      endCityDisabled: true,
      rules: {
        fromAddress: [{ required: true, message: '请选择起点城市', trigger: 'change' }],
        toAddress: [{ required: true, message: '请选择目的城市', trigger: 'change' }],
        vehicleModel: [{ required: true, message: '请选择车型', trigger: 'change' }],
        vehicleLength: [{ required: true, message: '请选择车身长', trigger: 'change' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }, {
          pattern: /^(\d{0,7})(\.(\d{0,2}))?$/g,
          message: "只能输入7位整数，2位小数",
          trigger: "blur"
        }],
        days: [{ required: true, trigger: 'blur', validator: validateAgingDays }],
        vehicleVolume: [{ required: true, message: '请输入容积', trigger: 'blur' }, {
          pattern: /^(\d{0,3})(\.(\d{0,2}))?$/g,
          message: "只能输入3位整数，2位小数",
          trigger: "blur"
        }],
        vehicleWeight: [{ required: true, message: '请输入载重', trigger: 'blur' }, {
          pattern: /^(\d{0,2})(\.(\d{0,2}))?$/g,
          message: "只能输入2位整数，2位小数",
          trigger: "blur"
        }],
        startAddress: [{ max: 100, message: '最多输入100个字符', trigger: 'blur' }],
        endAddress: [{ max: 100, message: '最多输入100个字符', trigger: 'blur' }],
      },
      props: {
        label: 'name',
        value: 'areaCode',
        checkStrictly: true
      },
      vehicleOptions: [],
      options: [],
      isFromLock: false,
      isEndLock: false
    }
  },
  computed: {
    statuss () {
      return Number(this.bargaStatus)
    },
    disabled () {
      return this.statuss === 3 ? false : this.statuss ? true : false
    },
    titleName () {
      let title = this.editStatus ? '编辑' : (this.statuss && this.statuss !== 3 ? '议价' : '新增');
      return title
    }
  },
  watch: {
    value: {
      handler ({ row }) {
        const { fromAddress, toAddress } = row;
        this.startCityDisabled = !(fromAddress?.districtCode);
        this.endCityDisabled = !(toAddress?.districtCode);
        this.ruleForm = row

        if (!this.ruleForm.vehicleWeight) {
          const vehicleLengthSttribute = this.ruleForm?.vehicleOptions?.find(desc => desc?.value === row?.vehicleLength);
          if (vehicleLengthSttribute) {
            const { load, volume } = vehicleLengthSttribute
            this.$set(this.ruleForm, 'vehicleWeight', load)
            this.$set(this.ruleForm, 'vehicleVolume', volume)
          }
        }
      }
    },
    editStatus: {
      handler (value) {
        this.headTitle = value
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handerInput (item) {
      this.$set(this.ruleForm, 'vehicleLength', '')
      this.$set(this.ruleForm, 'vehicleWeight', '')
      this.$set(this.ruleForm, 'vehicleVolume', '')
      this.ruleForm.vehicleOptions = item.length
      if (item.value === 11) {
        this.pressLoadLabel = '吨'
      }
    },
    handerVehicleLength (value) {
      let options = this.ruleForm.vehicleOptions || this.vehicleOptions
      if (value !== 999) {
        const { load, volume } = options.find(desc => desc.value === value) ?? {}
        this.$set(this.ruleForm, 'vehicleWeight', load)
        this.$set(this.ruleForm, 'vehicleVolume', volume)
      } else {
        this.$set(this.ruleForm, 'vehicleWeight', '')
        this.$set(this.ruleForm, 'vehicleVolume', '')
      }
      // this.vehicleLengthDetail = { load: this.ruleForm.load, volume: this.ruleForm.volume }
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$emit('add', { ...this.ruleForm, pressLoadLabel: this.pressLoadLabel || null })
        } else {
          return false;
        }
      });
    },
    handerFromLock () {
      this.isFromLock = !this.isFromLock
    },
    handerEndLock () {
      this.isEndLock = !this.isEndLock
    },
    inputUpdate () {
      this.$forceUpdate();
    },
    changeFrom (value) {
      this.ruleForm['fromAddress'] = value
      // value.districtCode ? this.startCityDisabled = false : this.startCityDisabled = true
      if (value?.districtCode) {
        this.startCityDisabled = false
      } else {
        this.startCityDisabled = true
        this.ruleForm.startAddress = ''
      }
    },
    changeTo (value) {
      this.ruleForm['toAddress'] = value
      // value.districtCode ? this.endCityDisabled = false : this.endCityDisabled = true
      if (value?.districtCode) {
        this.endCityDisabled = false
      } else {
        this.endCityDisabled = true
        this.ruleForm.endAddress = ''
      }
    },
    resetForm (formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: 0 10px;
}
.lock {
  padding-left: 10px;
}
.vehicle-flex {
  display: flex;
}
.vehicle-right {
  padding-left: 10px;
  color: var(--prev-color-primary);
}
.oper-status {
  padding: 0 0 10px 10px;
  font-weight: bold;
  border-bottom: 1px solid var(--prev-border-color-extra-grey);
  margin-bottom: 20px;
}
</style>